package viper.receiver.call;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import javax.media.Manager;
import javax.media.Player;

import viper.call.common.LiveStream;
import viper.main.StateManager;

public class CallReceiver implements Runnable {
	
	public final static CallReceiver INSTANCE = new CallReceiver();
	private CallReceiver(){
		
	}
	
	private LiveStream rxls = new LiveStream();
	private byte[] buff1 = null; //Storage for VHeader = 1 type packets
	private byte[] buff3; //Storage for VHeader = 3 type packets
	private byte[] buffrecovered=null; //also VHeader = 2
	
	private Player player = null;
	
	public void run() {

		//DataSource source = null;
		//PushBufferStream pbs = null;
		

		try {		
			// Construct a new socket on specified port.
			// All packets received on this port will be assumed to be VIPER packets.

			// Construct the custom PushBufferStream
			
			// Initialize receive stream with DataSource
			CustomDataSource rxcds = new CustomDataSource(rxls);
			rxcds.connect(); 

			// Construct and start the audio player
			player = Manager.createRealizedPlayer(rxcds);
			player.start();
			System.out.println("Starting player...");
			
		} catch (Throwable t) {
			t.printStackTrace();
		}
		
		System.out.println("run CallReceiver");
	}
	
	public void parsePacket(byte[] buff)
	{
		buff1= new byte[buff.length-1];
		System.arraycopy(buff,1,buff1,0,buff.length-1);
		rxls.update(buff1);
		
		/** DE-DIVERSIFICATION LOGIC **/
	// If packet is type 1, save payload into buff1 and update the stream since this packet wasn't encoded.
	
		/*if(buff[0]==1){ //Examine VIPER header...
			buff1= new byte[buff.length-1];
			System.arraycopy(buff,1,buff1,0,buff.length-1);
			//if(p!=null){
				//System.out.println("Packet Received!!");
				rxls.update(buff1);

			//}
		}
		// If packet is type 3, then decode using type 1 packet and update stream with recovered type 2 packet.
		else if(buff[0]==3){
			buff3= new byte[buff.length-1];
			buffrecovered= new byte[buff.length-1];
			System.arraycopy(buff,1,buff3,0,buff.length-1);
			//Perform the decoding with XOR...
			 for (int i =0;i<buff3.length;i++){
			     buffrecovered[i]=(byte)(buff1[i]^buff3[i]);
			     //.out.print(buffrecovered[i]);
			    }
			 //if(p!=null){
					//System.out.println("Packet Received!!");
					rxls.update(buffrecovered);
				//}
		}*/
	}
	
	public void end()
	{
		if(player!=null)
			player.stop();
		System.out.println("stop CallReceiver");
	}
}
